<template>
  <div class="alarmConfiguration zy-content">
    <search :columns="searchData" @getSearch="getSearch(arguments)"></search>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="toggleWarehouseDisplay" type="primary" size="small">
         
          <span  style="color: #fff;"> {{ isWarehouseCollapsed ? '展开仓库' : '折叠仓库' }}</span>
        </Button>
<!--        <Button @click="exportTemplateClick">
          {{ $t('common.batchExport') }}
        </Button>-->
      </div>
      <div class="tableContent">
        <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columns" ellipsis
               ref="selection" stripe :data="dataArr" @on-selection-change="onSelectChange" :span-method="spanMethod">
        </Table>
      </div>
<!--      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="delIds.length"/>
        <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
              @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
      </div>-->
    </div>
    
    <!-- 发货数量编辑模态框 -->
    <Modal v-model="showShipmentModal" title="编辑发货数量" :closable="true" @on-ok="handleSaveShipment">
      <div style="padding: 20px 0;">
        <Form ref="form" :model="editShipmentForm" :label-width="120">
        <FormItem label="发货数量">
          <Input v-model="editShipmentForm.shipmentQuantity" :min="0" placeholder="请输入发货数量"
                   style="width: 100%" class="inputBorder"></Input>
        </FormItem>
        </Form>
      </div>
    </Modal>
  </div>
</template>
<script>
import search from '@/components/curd/searchList.vue';
import fileDownload from 'js-file-download';
import Widget from '@/components/dataBoard/components/widget/index.vue';
import toggleTableOperation from '@/mixins/toggleTableOperation';
import * as echarts from 'echarts';
import {Modal, FormItem, Input} from 'iview';

export default {
  name: 'lostWorkingHours',
  components: {search, Widget, Modal, FormItem, Input},
  mixins: [toggleTableOperation],
  data() {
    return {
      allCheck: false,
      loading: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      isWarehouseCollapsed: false, // 仓库折叠状态
      searchData: [
        {
          title: '物料编号',
          key: 'materialCode'
        },
        {
          title: '物料名称',
          key: 'materialName'
        },
        {
          title: '项目名称',
          key: 'projectName'
        },
        {
          title: '客户名',
          key: 'customerName'
        },
        {
          title: '年',
          key: 'year',
          type: 'year',
          format: 'yyyy',
        },
        {
          title: '月',
          key: 'month',
          type: 'month',
          format: 'MM',
        },
      ],
      // 基础列配置
      baseColumns: [
        {
          title: '客户',
          key: 'customerName',
          width: 120,
          align: 'center',
          resizable: true,
          fixed: 'left',
        },
        {
          title: '项目名',
          key: 'projectName',
          width: 120,
          align: 'center',
          resizable: true,
          fixed: 'left',
        },
        {
          title: '物料编码',
          key: 'materialCode',
          width: 150,
          align: 'center',
          resizable: true,
          fixed: 'left',
        },
        {
          title: '物料名称',
          key: 'materialName',
          width: 150,
          align: 'center',
          resizable: true,
          fixed: 'left',
        },
        {
          title: '日期',
          key: 'dateType',
          width: 100,
          align: 'center',
          resizable: true,
          fixed: 'left',
        },
      ],
      columns: [], // 动态生成的完整列配置
      myChart: null,
      dataArr: [],
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      selection: [],
      checkBtnPermission: {},
      createByOptions: [],
      spanArr: {}, // 修改为对象，分别存储不同列的合并信息
      pos: 0, // 当前位置
      daysInMonth: 31, // 一个月的天数
      // 编辑发货数量相关
      showShipmentModal: false,
      editShipmentForm: {
        id: '',
        shipmentQuantity: 0
      },
    };
  },
  mounted() {
    this.searchList();
  },
  methods: {
    getSearch(arg) {
      this.searchParams = JSON.parse(JSON.stringify(arg[0]));
      this.pageNum = 1;
      this.searchList();
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },

    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },

    // 查询列表
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams,
      };
      this.axios({
        method: 'post',
        // url: '/dms/supply/marketing/balance/config/page',
        url: '/dms/supply/marketing/balance/recording/page',
        data: params,
      }).then((res) => {
        // 添加响应数据校验
        if (!res || !res.data || !Array.isArray(res.data.list)) {
          console.warn('数据格式不正确，使用空数组');
          this.dataArr = [];
          this.total = 0;
          this.columns = [...this.baseColumns];
          return;
        }
        
        // 使用模拟数据生成符合要求的表格数据
        const mockData = res.data.list;

        // 生成1-31日的固定列配置
        this.generateDynamicColumns();

        // 生成扁平化数据并设置到表格
        this.dataArr = this.generateFlatData(mockData);
        this.total = this.dataArr.length;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.dataArr = [];
        this.total = 0;
        this.columns = [...this.baseColumns];
      });
    },
    //勾选列表
    onSelectChange(selection) {
      let myArray = [];
      selection.map((item, index) => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    //导出
    exportTemplateClick() {
      let params = {
        delIds: this.delIds,
      };
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      const filName = '营销平衡报表';
      this.axios({
        url: '/dms/oee-board/abnormalShutdownReport/export',
        method: 'post',
        responseType: 'blob',
        data: params,
      }).then((res) => {
        fileDownload(res, filName + '.xls');
      });
    },
    // 生成1-31日的固定列配置
      generateDynamicColumns() {
        // 清空现有列配置
        this.columns = [...this.baseColumns];

        // 生成1-31日的固定列
        for (let day = 1; day <= this.daysInMonth; day++) {
          this.columns.push({
            title: day.toString(), // 使用日期中的日作为列标题
            key: `day_${day}`, // 使用日期作为key
            width: 100,
            align: 'center',
            resizable: true,
            // 自定义单元格模板，使发货数量可点击
            render: (h, params) => {
              const value = params.row[params.column.key];
              // 只有发货数量类型的行才显示为可点击
              if (params.row.dateType === '发货数量') {
                return h('span', {
                  class: 'shipment-clickable',
                  style: {
                    color: '#1890ff',
                    cursor: 'pointer'
                  },
                  on: {
                    click: (event) => {
                      this.handleShipmentClick(params.row, params.column, event);
                    }
                  }
                }, value);
              }
              return h('span', value);
            }
          });
        }
      },

    // 生成扁平化数据
    generateFlatData(data) {
      // 校验输入参数
      if (!Array.isArray(data)) {
        console.warn('数据格式不正确，返回空数组');
        return [];
      }
      
      const flatData = [];
      let recordTypes = ['发货数量', '实际生产', '现场库存', '仓库库存', '库存总数'];
      
      // 如果仓库折叠，过滤掉仓库库存和现场库存
      if (this.isWarehouseCollapsed) {
        recordTypes = recordTypes.filter(type => !['现场库存', '仓库库存'].includes(type));
      }

      // 为每个客户、项目、物料组合生成对应行数的数据（根据折叠状态）
      data.forEach(item => {
        // 校验item结构
        if (!item || typeof item !== 'object' || !item.materialList || !Array.isArray(item.materialList)) {
          console.warn('数据项格式不正确，跳过');
          return;
        }
        
        const customerName = item.customerName || '';
        const projectName = item.projectName || '';

        item.materialList.forEach(material => {
          // 校验material结构
          if (!material || typeof material !== 'object') {
            console.warn('物料数据格式不正确，跳过');
            return;
          }
          
          const materialCode = material.materialCode || '';
          const materialName = material.materialName || '';
          const recordingList = Array.isArray(material.recordingList) ? material.recordingList : [];

          // 生成5种记录类型的数据行
          recordTypes.forEach(type => {
            const row = {
              customerName,
              projectName,
              materialCode,
              materialName,
              dateType: type,
              recordingList: [] // 存储原始记录信息，用于发货数量编辑
            };

            // 初始化1-31日的所有列值为空
            for (let day = 1; day <= this.daysInMonth; day++) {
              row[`day_${day}`] = '';
            }

            // 遍历所有记录，将数据放入对应的日期列
            recordingList.forEach(record => {
              if (!record || !record.shiftTime) return;
              
              try {
                // 提取日期中的日部分
                const day = new Date(record.shiftTime).getDate();
                // 确保日期在1-31范围内
                if (day >= 1 && day <= this.daysInMonth) {
                  // 根据记录类型设置对应的数据
                  switch (type) {
                    case '发货数量':
                      row[`day_${day}`] = record.shipmentQuantity || 0;
                      // 存储记录ID，用于编辑发货数量
                      if (!row.recordingList[day]) {
                        row.recordingList[day] = [];
                      }
                      row.recordingList[day].push(record);
                      break;
                    case '实际生产':
                      row[`day_${day}`] = record.productionQuantity || 0;
                      break;
                    case '现场库存':
                      row[`day_${day}`] = record.liveQuantity || 0;
                      break;
                    case '仓库库存':
                      row[`day_${day}`] = record.inventoryQuantity || 0;
                      break;
                    case '库存总数':
                      row[`day_${day}`] = record.totalInventory || 0;
                      break;
                  }
                }
              } catch (error) {
                console.warn('日期解析错误:', error);
              }
            });

            flatData.push(row);
          });
        });
      });

      // 计算合并行信息
      this.calculateSpanArr(flatData);

      return flatData;
    },
    
    // 处理发货数量点击事件
    handleShipmentClick(row, column, event) {
      // 只有发货数量类型的行才允许编辑
      if (row.dateType !== '发货数量') return;
      
      // 获取列对应的日期
      const dayMatch = column.key.match(/day_(\d+)/);
      if (!dayMatch || !row.recordingList) return;
      
      const day = parseInt(dayMatch[1]);
      const records = row.recordingList[day];
      
      // 如果只有一条记录，直接编辑
      if (records && records.length === 1) {
        this.editShipmentForm = {
          id: records[0].id,
          shipmentQuantity: records[0].shipmentQuantity || 0
        };
        this.showShipmentModal = true;
      } else if (records && records.length > 1) {
        // 多条记录的情况，默认编辑第一条
        this.editShipmentForm = {
          id: records[0].id,
          shipmentQuantity: records[0].shipmentQuantity || 0
        };
        this.showShipmentModal = true;
      }
    },
    
    // 保存发货数量修改
    handleSaveShipment() {
      if (!this.editShipmentForm.id) {
        this.$Message.warning('请选择要编辑的记录');
        return;
      }
      
      const params = {
        id: this.editShipmentForm.id,
        shipmentQuantity: this.editShipmentForm.shipmentQuantity
      };
      
      this.axios({
        method: 'post',
        url: '/dms/supply/marketing/balance/recording/edit',
        data: params
      }).then((res) => {
        if (res && res.code === 200) {
          this.$Message.success('保存成功');
          this.showShipmentModal = false;
          // 重新加载数据
          this.searchList();
        } else {
          this.$Message.error(res.message || '保存失败');
        }
      }).catch(error => {
        console.error('保存失败:', error);
        this.$Message.error('保存失败，请重试');
      });
    },

    // 计算合并行信息
    calculateSpanArr(data) {
      // 初始化不同列的合并信息
      this.spanArr = {
        customerName: [], // 客户列的合并信息
        projectName: [], // 项目名列的合并信息
        materialCode: [], // 物料编码列的合并信息
        materialName: []  // 物料名称列的合并信息
      };

      // 校验数据是否存在且为数组
      if (!Array.isArray(data) || data.length === 0) {
        console.warn('没有数据可计算合并行信息');
        return;
      }

      try {
        // 计算客户列的合并信息
        this.calculateColumnSpan(data, 'customerName', this.spanArr.customerName);

        // 计算项目名列的合并信息
        this.calculateColumnSpan(data, 'projectName', this.spanArr.projectName);

        // 计算物料编码列的合并信息
        this.calculateColumnSpan(data, 'materialCode', this.spanArr.materialCode);

        // 计算物料名称列的合并信息
        this.calculateColumnSpan(data, 'materialName', this.spanArr.materialName);
      } catch (error) {
        console.error('计算合并行信息失败:', error);
        // 重置合并信息，避免显示错误
        this.spanArr = {
          customerName: new Array(data.length).fill(1),
          projectName: new Array(data.length).fill(1),
          materialCode: new Array(data.length).fill(1),
          materialName: new Array(data.length).fill(1)
        };
      }
    },

    // 计算指定列的合并信息
    calculateColumnSpan(data, columnKey, spanArray) {
      // 校验参数
      if (!Array.isArray(data) || !columnKey || !Array.isArray(spanArray)) {
        console.warn('参数格式不正确，无法计算合并信息');
        return;
      }

      if (data.length === 0) return;

      try {
        let sameValueCount = 1;
        let currentValue = data[0][columnKey];

        // 计算需要合并的行数
        for (let i = 1; i < data.length; i++) {
          if (data[i] && data[i][columnKey] === currentValue) {
            sameValueCount++;
          } else {
            for (let j = 0; j < sameValueCount; j++) {
              spanArray.push(j === 0 ? sameValueCount : 0);
            }
            currentValue = data[i] ? data[i][columnKey] : undefined;
            sameValueCount = 1;
          }
        }

        // 处理最后一组
        for (let j = 0; j < sameValueCount; j++) {
          spanArray.push(j === 0 ? sameValueCount : 0);
        }
      } catch (error) {
        console.error(`计算列 ${columnKey} 的合并信息失败:`, error);
        // 重置为默认不合并
        spanArray.length = 0;
        for (let i = 0; i < data.length; i++) {
          spanArray.push(1);
        }
      }
    },

    // 单元格合并方法
    spanMethod({row, column, rowIndex, columnIndex}) {
      // 校验参数
      if (!row || !column || rowIndex === undefined || columnIndex === undefined) {
        return;
      }

      // 校验spanArr是否存在
      if (!this.spanArr || typeof this.spanArr !== 'object') {
        return;
      }

      // 根据列索引确定对应的列名
      let columnKey;
      switch (columnIndex) {
        case 0: // 客户列
          columnKey = 'customerName';
          break;
        case 1: // 项目名列
          columnKey = 'projectName';
          break;
        case 2: // 物料编码列
          columnKey = 'materialCode';
          break;
        case 3: // 物料名称列
          columnKey = 'materialName';
          break;
        default:
          return; // 其他列不需要合并
      }

      try {
        // 获取对应列的合并信息，确保数组存在且索引有效
        const spanArray = this.spanArr[columnKey];
        if (!Array.isArray(spanArray) || rowIndex >= spanArray.length) {
          return;
        }
        
        const _row = spanArray[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      } catch (error) {
        console.error('单元格合并处理失败:', error);
      }
    },
    
    // 切换仓库显示状态
    toggleWarehouseDisplay() {
      this.isWarehouseCollapsed = !this.isWarehouseCollapsed;
      // 重新生成数据
      this.searchList();
    },
  },
};
</script>

<style scoped lang="scss">
.ivu-input-number {
  width: -webkit-fill-available;
}

.row_click {
  cursor: pointer;
  color: rgb(50, 113, 240) !important;
}

/* 确保固定列样式正确 */
:deep(.ivu-table-fixed-left) {
  box-shadow: 2px 0 6px 0 rgba(0, 0, 0, 0.05) !important;
}

/* 调整固定列单元格的内边距和对齐方式 */
:deep(.ivu-table-fixed-left .ivu-table-cell) {
  text-align: left;
  padding-left: 12px;
}

/* 发货数量可点击样式 */
:deep(.shipment-clickable) {
  transition: color 0.3s;
}

:deep(.shipment-clickable:hover) {
  color: #40a9ff !important;
  text-decoration: underline;
}
</style>
